/**
 * Created by kang on 2016/8/21.
 */
var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
var Log = require('../utils/logger');
var dbManager = require('../utils/db-manager');
var ObjectID = require('mongodb').ObjectID;

router.use(bodyParser.json()); // for parsing application/json
router.use(bodyParser.urlencoded({extended: true})); // for parsing application/x-www-form-urlencoded

router.restPath = "/result-apk";

router.get('/', function (req, res, next) {
    var logger = Log.getLogger("get result apk");
    //TODO:check the request body
    var resultApkCollection = dbManager.db.collection('ResultApk');
    resultApkCollection.find({}).toArray(function(error, result){
        if(error || !result){
            logger.error(error.name + ": " + error.message);
            res.status(404).json({
                name: error.name,
                message: error.message
            });
        }else{
            res.json(result);
        }
    })
});


/* new result apk */
router.post('/', function (req, res, next) {
    var logger = Log.getLogger("new result apk");

    //TODO:check the request body, file type check
    var resultApkBody = req.body;
    logger.info(resultApkBody);

    if(resultApkBody.name==undefined||resultApkBody.path==undefined
        ||resultApkBody.filename==undefined||resultApkBody.testPlanID==undefined) {
        logger.error("result apk: testPlanID, name, path, filename is required");
        res.status(404).json({
            message: "result apk: testPlanID, name, path, filename is required"
        }).end();
        return;
    }

    var resultApk = {
        testPlanID:resultApkBody.testPlanID,
        name:resultApkBody.name,
        path:resultApkBody.path,
        filename:resultApkBody.filename
    };

    var testPlanCollection = dbManager.db.collection('TestPlan');
    var obID;
    try {
        obID = new ObjectID(resultApk.testPlanID);
    } catch (error) {
        var msg = {
            name:"new ObjectID error",
            message:error.toString()
        };
        logger.error(msg);
        res.status(404).json(msg).end();
        return;
    }
    testPlanCollection.find({_id: obID}).next(function(err, result){
        if(err || !result){
            var error = {};
            error.name = err ? err.name : "New ResultApk error";
            error.message = err ? err.message :  "TestPlan of " + resultApk.testPlanID + " couldn't be found.";
            logger.error(error.name + ": " + error.message);
            res.status(404).json({
                name: error.name,
                message: error.message
            }).end();
            return;
        } else {
            var resultApkCollection = dbManager.db.collection('ResultApk');
            resultApkCollection.insertOne(resultApk).then(function(result){
                //location header of the response
                logger.info("resultApk created: "+ resultApk.toJSON);
                res.location(router.restPath + "/" + resultApk._id);
                res.status(201);
            }, function (error){
                logger.error("Save to collection:ResultApk failed");
                res.status(405).end();
                return;
            });

            testPlanCollection.updateOne({_id: new ObjectID(resultApk.testPlanID)},
                {$set:{'resultApkID': resultApk._id, 'lastRunStatus': 'Result Apk created'}})
                .then(function(result){
                    logger.info("TestPlan updated: "+ resultApk.testPlanID);
                }, function (error){
                    logger.error("TestPlan update failed");
                    res.status(405);
                });
            res.end();
        }
    });

});

/* get result apk info */
router.get('/:id', function (req, res, next){
    var tId = req.params.id;
    var logger = Log.getLogger("get resultApk with id" );
    logger.info(tId);

    //TODO:check the request body

    var obID;
    try {
        obID = new ObjectID(tId);
    } catch (error) {
        var msg = {
            name:"new ObjectID error",
            message:error.toString()
        };
        logger.error(msg);
        res.status(404).json(msg).end();
        return;
    }
    var testCodeCollection = dbManager.db.collection('ResultApk');
    testCodeCollection.find({_id: obID}).toArray(function(error, result){
        if(error){
            logger.error(error.name + ": " + error.message);
            res.status(404).json({
                name: error.name,
                message: error.message
            });
        }else{
            res.json(result);
        }
    })
});

/* download result apk */
router.get('/:id/apkfile', function (req, res, next){
    var tId = req.params.id;
    var logger = Log.getLogger("download resultApk with id" );
    logger.info(tId);

    //TODO:check the request body

    var obID;
    try {
        obID = new ObjectID(tId);
    } catch (error) {
        var msg = {
            name:"new ObjectID error",
            message:error.toString()
        };
        logger.error(msg);
        res.status(404).json(msg).end();
        return;
    }

    var testCodeCollection = dbManager.db.collection('ResultApk');
    testCodeCollection.find({_id: obID}).limit(1).next(function(error, result){
        if(error){
            logger.error(error.name + ": " + error.message);
            res.status(404).json({
                name: error.name,
                message: error.message
            });
        }else{
            try {
                var path = result.path;
                var filename = result.filename;
                logger.info(path);
                res.download(path + filename, filename);
            } catch (error) {
                var msg = {
                    name:"download error",
                    message:error.toString()
                };
                logger.error(msg);
                res.status(404).json(msg).end();
                return;
            }
        }
    })
});

module.exports = router;